<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Service;

use App\Dao\SendCodeLogDao;
use App\Utils\Logger;
use Hyperf\Di\Annotation\Inject;
use HyperfLibraries\Sms\Contract\SmsInterface;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;

class PhoneService
{
    /**
     * @Inject
     * @var SmsInterface
     */
    protected $sms;

    /**
     * @Inject
     * @var SendCodeLogDao
     */
    protected $sendCodeLogDao;

    /**
     * 发送手机验证码
     */
    public function sendAliPhoneCode(string $account): bool
    {
        try {
            //生成code
            $code = rand_code(6);
            $content = '您本次验证码为:' . $code;
            $ret = $this->sms->send($account, [
                'content' => $content,
                'template' => 'SMS_90340011',
                'data' => [
                    'code' => $code,
                ],
            ], ['aliyun']);
            if (isset($ret['aliyun']['status']) && $ret['aliyun']['status'] == 'success') {
                //写表记录
                $this->sendCodeLogDao->addLog($account, $code);
                return true;
            }
            return false;
        } catch (\Exception $e) {
            if ($e instanceof NoGatewayAvailableException) {
                Logger::writeLog(json_encode($e->getExceptions(), JSON_UNESCAPED_UNICODE), 'error', 'sms', 'sms');
            }
            return false;
        }
    }

    /**
     * 检查验证码
     * @param $account
     * @param $code
     */
    public function checkCode($account, $code): bool
    {
        $flag = false;
        $info = $this->sendCodeLogDao->getLog($account, $code);
        if (! empty($info)) {
            if (time() <= $info['expire_time']) {
                $flag = true;
            }
        }
        return $flag;
    }
}
